// pages/operation/index.js
const api = require('../../utils/api')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        type:"",
        uploaderList: [],
          uploaderNum:0,
          showUpload:true,
        index:"",
        showTime:false,
        currentDate: new Date().getTime(),
        carList:[],
        tabList:[],
        ifList:[
            {value:0,text:'否'},
            {value:1,text:'是 '}
        ],
        if1:'',
        if2:'',
        fileList: [
          
          ],
        obj:{
            name:"",
            type: "",
            brand: "",
            pricestr: "",
            mileage: "",
            age: "",
            status: 1,
            birthday: "",
            pic: "",
            price: "",
            minipic: "",
            recommend: "",
            quality: "",
            description: "",
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this
        that.setData({
            type:options.type
        })
        that.getCategoryList()
        if(that.data.type=='edit'){
            api.productinfo({
                id:options.id,
                method:"get",
                success: function(res){
                    that.setData({
                        obj:res.data.data.data.data,
                        if1:res.data.data.data.data.quality==1?'是':'否',
                        if2:res.data.data.data.data.recommend==1?'是':'否',
                        uploaderList:res.data.data.data.data.pic.split(";")
                    })
                }
            })
        }
    },
    bindinput(e){
        this.setData({
            'obj.description':e.detail.value
        })
    },
    // 删除图片
    clearImg:function(e){
        var nowList = [];//新数据
        var uploaderList = this.data.uploaderList;//原数据
        
        for (let i = 0; i < uploaderList.length;i++){
            if (i == e.currentTarget.dataset.index){
                continue;
            }else{
                nowList.push(uploaderList[i])
            }
        }
        this.setData({
            uploaderNum: this.data.uploaderNum - 1,
            uploaderList: nowList,
            showUpload: true
        })
    },
    //展示图片
    showImg:function(e){
        var that=this;
        wx.previewImage({
            urls: that.data.uploaderList,
            current: that.data.uploaderList[e.currentTarget.dataset.index]
        })
    },
    //上传图片
    upload: function(e) {
        var that = this;
        wx.chooseImage({
            count: 9 - that.data.uploaderNum, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function(res) {
               var nums  =0;
        var  getFiles= ()=> {
            wx.getFileInfo({
              filePath: res.tempFilePaths[0],
              success(files){
                  if(files.errMsg == "getFileInfo:ok"){
                      wx.uploadFile({
                        filePath:res.tempFilePaths[0],
                        name: 'filePath',
                        header: {
                            Accept: 'application/json',
                            'Content-Type': 'application/json',
                            authorization: wx.getStorageSync('token')
                          },
                        url: 'https://www.doudouxny.com/updateimg',
                        complete: function(files){
                            if( nums <5){
                                nums+=1;
                                if(files.errMsg="uploadFile:ok"){
                                    let tempFilePaths = JSON.parse(files.data).data;
                                    let uploaderList = that.data.uploaderList.concat(tempFilePaths);
                                    if (uploaderList.length==9){
                                        that.setData({
                                            showUpload:false
                                        })
                                    }
                                    that.setData({
                                        uploaderList: uploaderList,
                                        uploaderNum: uploaderList.length,
                                    })
                                    wx.showToast({
                                        title: '上传成功',
                                      })
                                }else{
                                    getFiles();
                                }
                            }
                        }
                      })
                  }
              }
            })
        }
        getFiles()
        // debugger
        //         if(res.errMsg=="chooseImage:ok"){
        //             wx.uploadFile({
        //                 filePath:res.tempFilePath,
        //                 name: 'name',
        //                 url: 'https://www.doudouxny.com/updateimg',
        //                 complete: function(res){
        //                     console.log(res,'aa')
        //                 }
        //             })
        //         }

                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片

            }
        })
    },
    onClickHide() {
       wx.navigateBack()
    },
    handleSubmit(){

        let obj = this.data.obj
        obj.pic = this.data.uploaderList.join(';')
        obj.status = 1
        obj.quality = obj.quality=='是'?1:0
        obj.recommend = obj.recommend=='是'?1:0
        obj.age =parseInt(obj.age)
        obj.mileage = parseInt(obj.mileage)
        obj.price = parseInt(obj.price)
        if(this.data.type=='add'){
            api.productadd({
                data: {
                    productdata:obj,
                    opcode:"111",
                },
                method:'post',
                success(res){
                    console.log(res)
                    if(res.data.success==true){
                        wx.showToast({
                          title: '上传成功',
                        })
                        wx.navigateBack({
                          delta: 0,
                        })
                    }
                }
            })
        }
        if(this.data.type=='edit'){
            api.productupdate({
                data: {
                    productdata:obj,
                    opcode:"111",
                },
                method:'post',
                success(res){
                    console.log(res)
                    if(res.data.success==true){
                        wx.showToast({
                          title: '上传成功',
                        })
                        wx.navigateBack({
                          delta: 0,
                        })
                    }
                }
            })
        }
    },
    onInput(event) {
        var date = new Date(event.detail);
      var Y = date.getFullYear() + '-';
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1)+ '-' ;
      var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) ;
      var strDate = Y + M +D 
        this.setData({
          'obj.birthday':strDate,
        });
      },
    showTime(){
        this.setData({
            showTime:true
        })
    },

    onChange(e){
        this.setData({
            'obj.name':e.detail
        })
        
    },
    getYmd(s,type) {
        // var s = "2010-5-6";
        let a = s.split("-");
        if (a.length > 2) {
          let y = a[0];
          let m = a[1];
          let d = a[2];
          console.log('y:'+y,'m:'+m,'d:'+d)
          let returnStr = '';
          switch(type){
            case 'y':
              returnStr = y;
              break;
            case 'm':
              returnStr = m;
              break;
            case 'd':
              returnStr = d;
              break;
            default:
              returnStr = '';
              break;
          }
          return returnStr;
        }else{
          return '';
        }
      },
    getAge(birthday) {
        let iage = 0;
        if (birthday) {
          //获取出生日期的年月日
          let year = this.getYmd(birthday,'y');
          let month = this.getYmd(birthday, 'm');
          let day = this.getYmd(birthday, 'd');
     
       //获取当前时间的年月日
          let myDate = new Date();
          let now_year = myDate.getFullYear(); 
          let now_month = myDate.getMonth()+1; 
          let now_day = myDate.getDate(); 
     
          if (now_year > year) {
            iage = now_year - year - 1;
            if (now_month > month) {
              iage++;
            } else if (now_month == month) {
              if (now_day >= day) {
                iage++;
              }
            }
          }
        }
        return iage;
      },
    onChange2(e){
        this.setData({
            'obj.price':e.detail
        })
    },
    onChange3(e){
        this.setData({
            'obj.age':e.detail
        })
    },
    onChange5(e){
        this.setData({
            'obj.mileage': e.detail
        })
    },
    confirmTime(e){
        this.setData({
            showTime:false,
            'obj.age':parseInt(this.getAge(this.data.obj.birthday))
        })

    },
    getCategoryList(){
        // 初始化车辆
        api.getCategoryList({
            data: {
                opcode: "1",
                pagesize: 10,
                page: 1,
              }
            ,
            success:(res)=>{
                let data = res.data.data.data
                var category = {
                    1001: "车型",
                    1002: "品牌",
                    1003: "价格",
                    1004: "公里数",
                    1005: "车龄",
                  };
                  let dataList = new Array();
                  let child = new Array();
                  let dataDict = {};
                  for (let k in data) {
                    dataDict["id"] = Number(k);
                    dataDict["name"] = category[k];
                    for (let j in data[k]) {
                      data[k][j] = JSON.parse(data[k][j]);
                      data[k][j]["id"] = Number(j);
                      child.push(data[k][j]);
                    }
                    dataDict["child"] = child;
                    dataList.push(dataDict);
                    dataDict = {};
                    child = [];
                  }
                    let data2 = dataList.map((item)=>{
                        return {
                        }
                    })
                    let newArr = []
                    for(let i=0 ;i<dataList.length;i++){
                        let option1 = dataList[i].child.map((item)=>{
                            return {
                                text:item.nickname,
                                value:item.id
                            }
                        })
                        newArr.push(option1)
                    }
                  this.setData({
                    tabList:newArr
                  })
            }
        })
    },
    bindPicker1(e){
        this.setData({
            if1:this.data.ifList[e.detail.value].text,
            'obj.quality':this.data.ifList[e.detail.value].value,
            index:""
        })
    },
    bindPicker2(e){
        this.setData({
            if2:this.data.ifList[e.detail.value].text,
            'obj.recommend':this.data.ifList[e.detail.value].value,
            index:""
        })
    },
    bindPickerChange(e){
        this.setData({
            'obj.type':this.data.tabList[0][parseInt(e.detail.value)].text,
            index:""
        })
    },
    bindPickerChange2(e){
        this.setData({
            'obj.brand':this.data.tabList[1][parseInt(e.detail.value)].text,
            index:""
        })
    },
    bindPickerChange3(e){
        this.setData({
            
            'obj.mileage':this.data.tabList[3][parseInt(e.detail.value)].value,
            index:""
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})